#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<string.h>

const int MAX_KEY_NUM = 128;
const int MAX_KEY_LENGTH = 1024;

// char gKeys[MAX_KEY_NUM][MAX_KEY_LENGTH];

char *GetIniKeyString(char *title, char *key, char *filename)
{
    FILE *fp;
    int flag = 0;
    char sTitle[32], *wTmp;
    char sLine[MAX_KEY_LENGTH];

    sprintf(sTitle, "[%s]", title);
    if (NULL == (fp = fopen(filename, "r")))
    {
        perror("fopen");
        return NULL;
    }

    while (NULL != fgets(sLine, MAX_KEY_LENGTH, fp))
    {
        /// 这是注释行  ///
        if (0 == strncmp("//", sLine, 2))
            continue;
        if ('#' == sLine[0])
            continue;

        wTmp = strchr(sLine, '=');
        if ((NULL != wTmp) && (1 == flag))
        {
            if (0 == strncmp(key, sLine, wTmp - sLine)) /// 长度依文件读取的为准  ///
            {
                sLine[strlen(sLine) - 1] = '\0';
                fclose(fp);
                return wTmp + 1;
            }
        }
        else
        {
            if (0 == strncmp(sTitle, sLine, strlen(sLine) - 1)) /// 长度依文件读取的为准  ///
            {
                flag = 1; /// 找到标题位置  ///
            }
        }
    }
    fclose(fp);
    return NULL;
}

int main(int argc, char **argv)
{

    char *ipOne = (char *)malloc(100 * sizeof(char));
    strcpy(ipOne, GetIniKeyString("IPSite", "socketOneIp", "config.ini"));
    printf("ipOne is %s\n", ipOne);

    char *portOne = (char *)malloc(100 * sizeof(char));
    strcpy(portOne, GetIniKeyString("IPSite", "socketOnePort", "config.ini"));
    printf("portOne is %s\n", portOne);

    char *ipTwo = (char *)malloc(100 * sizeof(char));
    strcpy(ipTwo, GetIniKeyString("IPSite", "socketTwoIp", "config.ini"));
    printf("ipTwo is %s\n", ipTwo);

    char *portTwo = (char *)malloc(100 * sizeof(char));
    strcpy(portTwo, GetIniKeyString("IPSite", "socketTwoPort", "config.ini"));
    printf("portTwo is %s\n", portTwo);

    return 0;
}